package com.ss.whisper2.service.impl;

import com.ss.whisper2.dao.FileDao;
import com.ss.whisper2.pojo.entity.FileInfo;
import com.ss.whisper2.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;


@Service
public class FileServiceImpl implements FileService {

	private static final Logger LOGGER = LoggerFactory.getLogger(FileServiceImpl.class);

	@Value("${filepath}")
	private String fileHostPath;

	@Autowired
	FileDao fileDao;

	@Override
	public List<FileInfo> getFileList() {
		return fileDao.getFileList();
	}

	@Override
	public String upload(MultipartFile file) {
		System.out.println(fileHostPath);
		File test = new File(fileHostPath+file.getOriginalFilename());
		if (!test.exists()){
			test.mkdirs();
		}
		try {
			file.transferTo(test);
		}catch (IOException e){
			LOGGER.error(file.getOriginalFilename()+"文件上传失败", e);
		}
		return "文件上传成功";
	}

	@Override
	public String download(String fileName, HttpServletResponse response){
		File file = new File(fileHostPath + fileName);
		if (!file.exists()){
			return "文件不存在";
		}
		byte[] bytes = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);

			response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
			response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
			os = response.getOutputStream();
			int length;
			while ((length = bis.read(bytes)) != -1){
				os.write(bytes, 0, length);
			}
			os.flush();
		}catch (Exception e){
			LOGGER.error("文件下载失败", e);
		}finally {
			try {
				if (bis != null){
					bis.close();
				}

				if (os != null){
					os.close();
				}

				if (fis != null){
					fis.close();
				}
			}catch (IOException e){
				LOGGER.error(e.getMessage(), e);
			}
		}
		return "成功";
	}

	@Override
	public void record(String username, String fileName) {
		FileInfo fileInfo = new FileInfo();
		fileInfo.setName(fileName);
		fileInfo.setUsername(username);
		fileDao.record(fileInfo);
	}
}
